class R3G_AIController2 extends AIController;

// Ground speed of the pawn, display as Ground Speed in the editor
var(Pawn) const float UserGroundSpeed<DisplayName=Ground Speed>;

var Actor Target;

event Possess(Pawn inPawn, bool bVehicleTransition)
{
    super.Possess(inPawn, bVehicleTransition);
    Pawn.SetMovementPhysics();
}

simulated event PostBeginPlay() 
{
    super.PostBeginPlay();
}

simulated function Tick(float DeltaTime)
{
	local PlayerController PlayerController;
	local Vector Direction;
	local Rotator NewRotation;

	Super.Tick(DeltaTime);

	// If we don't have an enemy yet...
	if (Enemy == None)
	{
		// Find the player controller in the world
		PlayerController = GetALocalPlayerController();
		if (PlayerController != None && PlayerController.Pawn != None)
		{
			// Set the enemy to the player controller's pawn
			Enemy = PlayerController.Pawn;
		}
	}
	else
	{
		// Find the direction in order for me to look at my enemy
		Direction = Enemy.Location - Location;
		// Only need to use the yaw from the direction
		NewRotation = Rotator(Direction);
		NewRotation.Pitch = 0;
		NewRotation.Roll = 0;
		// Set the rotation so that I look at the enemy
		SetRotation(NewRotation);
		// Set my velocity, so I move towards the enemy
		Velocity = Normal(Enemy.Location - Location) * UserGroundSpeed;
		// Set my acceleration, so I move towards the enemy
		Acceleration = Velocity;
	}
}

state Follow
{
    function bool FindNavMeshPath()
    {
        // Clear cache and constraints (ignore recycling for the moment)
        NavigationHandle.PathConstraintList = none;
        NavigationHandle.PathGoalList = none;

        // Create constraints
        class'NavMeshPath_Toward'.static.TowardGoal( NavigationHandle, Target );
        class'NavMeshGoal_At'.static.AtActor( NavigationHandle, Target, 32 );

        // Find path
        return NavigationHandle.FindPath();
    }

Begin:

    if( NavigationHandle.ActorReachable( target) )
    {
        FlushPersistentDebugLines();
        //Direct move
        MoveToward( target,target );
    }
    else if( FindNavMeshPath() )
    {
        NavigationHandle.SetFinalDestination(target.Location);
        FlushPersistentDebugLines();
        NavigationHandle.DrawPathCache(,TRUE);
        
        // move to the first node on the path
    }
}


state Shoot
{
    function Aim()
    {
        local Rotator final_rot;
		local Vector wpDirect;
		wpDirect = (Target.Location - Pawn.Location);

        final_rot = Rotator(wpDirect); //Look straight up
        Pawn.SetViewRotation(final_rot);
    }
Begin:
    Pawn.ZeroMovementVariables();
    Sleep(1); //Give the pawn the time to stop.
    Aim();
    Pawn.StartFire(1);
	`log("fire");
    Pawn.StopFire(1);
    GotoState('Follow');
}

defaultproperties
{
    	// Ground speed of the pawn
	UserGroundSpeed=150.f
}
